//
//  CreditViewController.swift
//  Automobile
//
//  Created by erkebulan elzhan on 7/26/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit

final class CreditViewController: UIViewController {

    // MARK: - Outlets
    private lazy var creditTF: PlaceholderTF = {
        let field = PlaceholderTF(placeholder: "Сумма кредита", text: "0 ₸", kType: .numberPad)
        return field
    }()
    private lazy var srokTF: PlaceholderTF = {
        let field = PlaceholderTF(placeholder: "Срок кредита", text: "0 лет", kType: .numberPad)
        return field
    }()
    private lazy var submitBtn: UIButton = {
        let button = UIButton()
        button.backgroundColor = .blueColor
        button.setTitle("Отправить", for: .normal)
        button.clipsToBounds = true
        button.layer.cornerRadius = 15
        button.titleLabel!.font = UIFont.systemFont(ofSize: 17, weight: .medium)
        button.titleLabel?.textColor = .white
        return button
    }()
    private lazy var commentLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.font = UIFont.systemFont(ofSize: 15, weight: .regular)
        label.textColor = .greyColor
        label.textAlignment = .left
        
        let str = "Услуги оказываются АО CenterCredit. Пример расчкта условий по кредиту носит исключительно информационный характер и не является публичной офертой. Auto Nomad не несёт ответственности за действия третьих лиц."
        let attrString = NSMutableAttributedString(string: str)
        var style = NSMutableParagraphStyle()
        style.lineSpacing = 8
        attrString.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: NSRange(location: 0, length: str.count))
        label.attributedText = attrString
        return label
    }()
    
    // MARK: - Properties
    
    private var infoRows = [
        InfoView.Row(placeholder: "Платеж в месяц",
                     value: "0 ₸", isMarked: true),
        InfoView.Row(placeholder: "Первый взнос",
                     value: "0 ₸", isMarked: false),
        InfoView.Row(placeholder: "Процентная ставка",
                     value: "0 %", isMarked: false)
    ]
    
    private lazy var infoView = InfoView(rows: infoRows)
    
        /// Full-values of text fields
    private var creditValue = 0 {
        didSet {
            self.updateInfoView()
        }
    }
    private var srokValue = 0 {
        didSet {
            self.updateInfoView()
        }
    }
    
    // MARK: - Actions
    
    /// dismiss current view controller
    @objc private func goBack (sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    /// update info view
    private func updateInfoView () {
        if (creditValue != 0 && srokValue != 0) {
            infoRows[0].value = "\(Int(CreditManager.shared.getFirstInvest(overall: Double(creditValue)))) ₸"
            infoRows[1].value = "\(CreditManager.shared.getFirstInvest(overall: Double(creditValue))) ₸"
            infoRows[2].value = "\(CreditManager.shared.getStavka())%"
            self.infoView.updateUI(rows: infoRows)
        }
    }
    
    
    // MARK: - Life-Cycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.setUpUI()
        self.setUpFields()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        self.setUpNav()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        self.navigationController?.navigationBar.isHidden = true
        self.tabBarController?.tabBar.isHidden = false
    }
    
    // MARK: - UI

    private func setUpNav () {
        self.view.backgroundColor = .white
        self.navigationController?.navigationBar.isHidden = false
        self.navigationController?.navigationBar.defaultNavBar()
        let backIcon = UIImage(named: "cancel")
        let backButton = UIBarButtonItem(image: backIcon, landscapeImagePhone: backIcon, style: .plain, target: self, action: #selector(goBack(sender:)))
        backButton.tintColor = .greyColor
        self.navigationItem.simpleNavBar(title: "Мои заявки", backButton: backButton)
    }
    
    private func setUpUI () {
        self.view.addSubview(creditTF)
        self.view.addSubview(srokTF)
        self.view.addSubview(infoView)
        self.view.addSubview(submitBtn)
        self.view.addSubview(commentLabel)
        creditTF.snp.makeConstraints { (make) in
            make.top.equalTo(view.safeAreaLayoutGuide).inset(16)
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(60)
        }
        srokTF.snp.makeConstraints { (make) in
            make.height.equalTo(60)
            make.leading.trailing.equalToSuperview().inset(16)
            make.top.equalTo(creditTF.snp.bottom).offset(16)
        }
        infoView.snp.makeConstraints { (make) in
            make.leading.trailing.equalToSuperview().inset(16)
            // make.height.equalTo(150)
            make.top.equalTo(srokTF.snp.bottom).offset(16)
        }
        submitBtn.snp.makeConstraints { (make) in
            make.top.equalTo(infoView.snp.bottom).offset(16)
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(44)
        }
        commentLabel.snp.makeConstraints { (make) in
            make.bottom.equalTo(view.safeAreaLayoutGuide).inset(48)
            make.leading.trailing.equalToSuperview().inset(16)
        }
    }
    
    /// TextFields
    
    private func setUpFields () {
        creditTF.textField.addTarget(self, action: #selector(fieldChanged(sender:)), for: .editingChanged)
        srokTF.textField.addTarget(self, action: #selector(fieldChanged(sender:)), for: .editingChanged)
    }
    
    @objc func fieldChanged (sender: UITextField) {
        if (sender == creditTF.textField) {
            creditValue = Int(sender.text ?? "0") ?? 0
        } else {
            srokValue = Int(sender.text ?? "0") ?? 0
        }
    }
}
